package gemini.pollux.ui.client.page.content.product.product.list;

import gemini.basic.model.Product;
import gemini.basic.model.ProductType;
import gemini.pollux.ui.client.page.content.product.product.widget.ProductTableWidget;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;

public class ProductListView extends Composite implements
		ProductListPresenter.Display {

	@UiTemplate("ProductListView.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, ProductListView> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public ProductListView() {
		initWidget(binder.createAndBindUi(this));
	}
	
	private List<ProductType> productTypes;
	
	
	@UiField
	ListBox lbxProductType;
	
	@UiHandler("lbxProductType")
	void onChangeProductType(ChangeEvent event){
		if(products != null && !products.isEmpty()){
			if(lbxProductType.getSelectedIndex() == 0){
				prwProductList.loadData(products);
			} else {
				prwProductList.loadData(getProductsByType(Integer
						.parseInt(lbxProductType.getValue(lbxProductType
								.getSelectedIndex()))));
			}
		}
	}

	@UiField
	HTML htmTitle;

	@UiField
	HTML htmInformation;

	@UiField
	ProductTableWidget prwProductList;
	
	@Override
	public ProductTableWidget getProductTableWidget(){
		return prwProductList;
	}
	
	private List<Product> products;

	private List<Product> getProductsByType(int typeId) {
		List<Product> result = new ArrayList<Product>(products.size());
		for (Product pr : products) {
			if (pr.getProductType().getId() == typeId) {
				result.add(pr);
			}
		}
		return result;
	}

	@Override
	public void showProducts(List<Product> products){
		this.products = products;
		prwProductList.loadData(products);
	}

	@Override
	public void initCustom() {
		htmTitle.setHTML("<h3>Product List</h3>");
		htmInformation.setHTML("Products information");
		
		lbxProductType.setWidth("300px");
		
		lbxProductType.clear();
		lbxProductType.addItem("All", "0");
		if (productTypes != null) {
			for (ProductType prT : productTypes) {
					lbxProductType.addItem(prT.getName(),
							String.valueOf(prT.getId()));
			}
		}
	}

	@Override
	public Widget asWidget() {
		return this;
	}
	
	@Override
	public void setProductTypes(List<ProductType> productTypes) {
		this.productTypes = productTypes;
	}
}
